from rest_framework.viewsets import ModelViewSet
from rest_framework.generics import ListAPIView
from rest_framework.views import APIView
from rest_framework.response import Response

from apps.goods.models import SKU, GoodsCategory, SPU, SPUSpecification
from apps.meiduo_admin.utils import PageNum
from apps.meiduo_admin.serializers.sku import SKUSerializer, SKUCategoriesSerializer, SPUSimpleSerializer, SPUSpecSerializer


class SKUModelViewSet(ModelViewSet):
    """sku展示页面"""

    # 页面展示与查询
    # 接受参数keyword，判断是展示页面还是查询
    # 重新定义get_queryset
    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword:
            skus = SKU.objects.filter(name__contains=keyword).order_by('-price')
        else:
            skus = SKU.objects.all().order_by('id')

        return skus

    # 指定序列化器
    serializer_class = SKUSerializer
    # 指定分页器
    pagination_class = PageNum


class SKUCategoriesView(ListAPIView):
    """新增页面，三级分类"""
    # 获取查询集(商品的三级分类)
    queryset = GoodsCategory.objects.filter(subs=None)
    # 指定序列化器
    serializer_class = SKUCategoriesSerializer


class SPUSimpleView(ListAPIView):
    """新增页面，SPU名称（可以和三级分类关联）"""
    # 获取查询集
    queryset = SPU.objects.all()
    # 指定序列化器
    serializer_class = SPUSimpleSerializer


class SPUSpecView(APIView):
    """
    获取对应的商品规格
    因为要根据SPU名称获取对应的商品规格，所以要用APIView，写get方法，传入SPU的pk
    """
    def get(self, request, pk):

        # 获取查询集
        qs = SPUSpecification.objects.filter(spu_id=pk)
        # 指定序列化器
        serializer = SPUSpecSerializer(qs, many=True)
        # 响应结果
        return Response(serializer.data)
